<script setup>
import { addCateService, getCategoriesListService, getParentCateListService } from '@/api/goods'
import { ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

const queryInfo = ref({
  type: 3,
  pagenum: 1,
  pagesize: 5,
})
const cateList = ref([])
const total = ref(0)
//   为table指定列的定义

async function getCategoriesList() {
  const { data: res } = await getCategoriesListService(queryInfo.value)
  if (res.meta.status !== 200) {
    return ElMessage.error('获取商品分类列表失败')
  }

  cateList.value = res.data.result
  total.value = res.data.total
}
onMounted(() => {
  getCategoriesList()
})
const expandConfig = ref({
  showIcon: true,
  iconOpen: 'vxe-icon-square-minus',
  iconClose: 'vxe-icon-square-plus',
})

function handleCurrentChange(newPageNum) {
  queryInfo.value.pagenum = newPageNum
  getCategoriesList()
}
function handleSizeChange(newPageSize) {
  queryInfo.value.pagesize = newPageSize
  getCategoriesList()
}

// add
const addCateDialogVisible = ref(false)
const parentCateList = ref([])
const addCateForm = ref({
  // 将要添加的分类的名称
  cat_name: '',
  // 父级分类的id
  cat_id: 0,
  // 分类的等级默认添加的是1级分类
  cat_level: 0,
})
const addCateFormRules = {
  cat_name: [
    { required: true, message: '请输入分类的名称', trigger: 'blur' },
  ],
}
const addCateFormRef = ref()
const selectedKeys = ref([])
const cascaderProps = ref({
  label: 'cat_name',
  children: 'children',
  value: 'cat_id',
  checkStrictly: true,
  expandTrigger: 'hover',
})

function addCateDialogClosed() {
  addCateFormRef.value.resetFields()
  selectedKeys.value = []
  addCateForm.value.cat_level = 0
  addCateForm.value.cat_pid = 0
}
function showAddCateDialog() {
  getParentCateList()
  addCateDialogVisible.value = true
}
async function getParentCateList() {
  const { data: res } = await getParentCateListService(2)
  if (res.meta.status !== 200) {
    return ElMessage.error('获取父级分类失败')
  }
  parentCateList.value = res.data
  // console.log(res)
}
// 选择项发生改变
function parentCateChanged() {
  // 如果selectedKeys数组中的length大于0，证明选中了父级分类
  // 反之，就说明没有选中任何父级分类
  if (selectedKeys.value.length > 0) {
    addCateForm.value.cat_pid = selectedKeys.value[selectedKeys.value.length - 1]
    addCateForm.value.cat_level = selectedKeys.value.length
  }
  else {
    addCateForm.value.cat_id = 0
    addCateForm.value.cat_level = 0
  }
}
function addCate() {
  addCateFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    const { data: res } = await addCateService(addCateForm.value)
    if (res.meta.status !== 201) {
      return ElMessage.error('添加分类失败')
    }
    ElMessage.success('添加分类成功')
    getCategoriesList()
    addCateDialogVisible.value = false
  })
}
</script>

<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <el-button type="primary" @click="showAddCateDialog">
        添加分类
      </el-button>
      <!-- 表格区域 -->
      <vxe-table :expand-config="expandConfig" border :data="cateList">
        <vxe-column type="seq" title="序号" width="60" />
        <!-- 展开行 -->
        <vxe-column type="expand" width="60">
          <template #content="{ row }">
            <div class="expand-wrapper">
              <vxe-table border :data="row.children" height="200">
                <vxe-column field="cat_name" title="分类名称" />
                <vxe-column field="cat_pid" title="是否有效">
                  <template #default="scope">
                    <vxe-tag v-if="scope.row.cat_pid === 0" status="success">
                      有效
                    </vxe-tag>
                    <vxe-tag v-else status="error">
                      无效
                    </vxe-tag>
                  </template>
                </vxe-column>
                <vxe-column field="cat_level" title="排序">
                  <template #default="scope">
                    <vxe-tag v-if="scope.row.cat_level === 0 " status="primary">
                      一级
                    </vxe-tag>
                    <vxe-tag v-else-if="scope.row.cat_level === 1 " status="primary">
                      二级
                    </vxe-tag>
                  </template>
                </vxe-column>
                <vxe-column title="操作">
                  <template #default="scope">
                    <vxe-button content="编辑" status="primary" icon="vxe-icon-edit" />
                    <vxe-button content="删除" status="error" icon="vxe-icon-delete" />
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="cat_name" title="分类名称" />
        <vxe-column field="cat_pid" title="是否有效">
          <template #default="scope">
            <vxe-tag v-if="scope.row.cat_pid === 0" status="success">
              有效
            </vxe-tag>
            <vxe-tag v-else status="error">
              无效
            </vxe-tag>
          </template>
        </vxe-column>
        <vxe-column field="cat_level" title="排序">
          <template #default="scope">
            <vxe-tag v-if="scope.row.cat_level === 0 " status="primary">
              一级
            </vxe-tag>
          </template>
        </vxe-column>
        <vxe-column title="操作">
          <template #default="scope">
            <vxe-button content="编辑" status="primary" icon="vxe-icon-edit" />
            <vxe-button content="删除" status="error" icon="vxe-icon-delete" />
          </template>
        </vxe-column>
      </vxe-table>

      <!-- 分页区域 -->
      <el-pagination
        v-model:current-page="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[3, 5, 10, 15]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      v-model="addCateDialogVisible"
      title="添加分类"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form ref="addCateFormRef" :rules="addCateFormRules" :model="addCateForm" label-width="120px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name" />
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader v-model="selectedKeys" :props="cascaderProps" :options="parentCateList" @change="parentCateChanged" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCate">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.vxe-table {
  margin-top: 15px;
}
</style>
